<template>
  <div class="right-board">
    <el-tabs v-model="currentTab" class="center-tabs">
      <el-tab-pane label="组件属性" name="field" />
      <el-tab-pane label="组件样式" name="style" />
    </el-tabs>
    <div class="field-box">
      <el-scrollbar class="right-scrollbar">
        <el-form size="small"  v-show="currentTab==='field' && showField" label-width="90px" labelPosition="left">
          <template v-if="activeData.config">
            <BaseSetting :activeData="activeData" :allComps = "allComps"></BaseSetting>
            <template v-if="hasTable">
                <template v-if="activeData.config.pfKey==='table'">
                  <el-form-item
                    v-if="activeData.vModel!==undefined && !noVModelList.includes(activeData.config.pfKey)  ||activeData.config.isStorage==2 "
                    label="控件字段">
                    <el-input v-model="activeData.vModel" placeholder="请输入数据库字段" disabled />
                  </el-form-item>
                </template>
                <template v-else>
                  <template v-if="!activeData.config.isSubTable">
                    <template
                      v-if="activeData.config.pfKey==='calculate' ||activeData.config.pfKey==='popupAttr' ||activeData.config.pfKey==='relationFormAttr'">
                      <el-form-item label="控件类型">
                        <el-select v-model="activeData.config.isStorage" placeholder="请选择"
                          @change="changeStorage">
                          <el-option :label="item.label" :value="item.value"
                            v-for="(item,i) in storageType" :key="i"></el-option>
                        </el-select>
                      </el-form-item>
                    </template>
                    <el-form-item
                      v-if="activeData.vModel!==undefined && !noVModelList.includes(activeData.config.pfKey)  ||activeData.config.isStorage==2"
                      label="数据库表">
                      <el-select v-model="activeData.config.tableName" placeholder="请选择数据库表"
                        @change="tableChange" filterable>
                        <el-option v-for="item in allTable" :key="item.tableName" :value="item.tableName"
                          :label="item.remarks?item.tableName+'('+item.remarks+')':item.tableName">
                          <span class="custom-option-left">
                            {{ item.remarks?item.tableName+'('+item.remarks+')':item.tableName}}
                          </span>
                          <span class="custom-option-right">{{item.typeId=='1'?'主表':'从表'}}</span>
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item
                      v-if="activeData.vModel!==undefined && !noVModelList.includes(activeData.config.pfKey) ||activeData.config.isStorage==2 "
                      label="控件字段">
                      <el-select v-model="activeData.vModel" placeholder="请选择数据库字段" clearable
                        @change="fieldChange" filterable popper-class="field-select-popper">
                        <p class="el-select-dropdown__empty" slot="empty">
                          <span>无匹配数据，</span>
                          <!-- <el-link type="primary" :underline="false" @click="openFieldDialog">添加字段
                          </el-link> -->
                        </p>
                        <!-- <el-option-group label="" v-if="fieldOptions.length">
                          <el-option disabled value="-">
                            <el-link type="primary" :underline="false" @click="openFieldDialog">添加字段
                            </el-link>
                          </el-option>
                        </el-option-group> -->
                        <el-option-group label="">
                          <el-option v-for="item in fieldOptions" :key="item.columnHumpName"
                            :value="item.columnHumpName"
                            :label="item.remarks?item.remarks+'('+item.columnHumpName+')':item.columnHumpName">
                          </el-option>
                        </el-option-group>
                      </el-select>
                    </el-form-item>
                  </template>
                  <template v-if="activeData.config.isSubTable && subTable.length">
                    <template
                      v-if="activeData.config.pfKey==='calculate' ||activeData.config.pfKey==='popupAttr' ||activeData.config.pfKey==='relationFormAttr'">
                      <el-form-item label="控件类型">
                        <el-select v-model="activeData.config.isStorage" placeholder="请选择"
                          @change="changeStorage">
                          <el-option :label="item.label" :value="item.value"
                            v-for="(item,i) in storageType" :key="i"></el-option>
                        </el-select>
                      </el-form-item>
                    </template>
                    <el-form-item label="数据库表">
                      <el-select v-model="activeData.config.relationTable" placeholder="请选择数据库表"
                        filterable disabled>
                        <el-option v-for="item in allTable" :key="item.tableName" :value="item.tableName"
                          :label="item.remarks?item.tableName+'('+item.remarks+')':item.tableName">
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item
                      v-if="activeData.vModel!==undefined && !noVModelList.includes(activeData.config.pfKey) ||activeData.config.isStorage==2"
                      label="控件字段">
                      <el-select v-model="activeData.vModel" placeholder="请选择数据库字段" clearable
                        @change="fieldChange1" filterable>
                        <p class="el-select-dropdown__empty" slot="empty">
                          <span>无匹配数据，</span>
                          <!-- <el-link type="primary" :underline="false" @click="openFieldDialog">添加字段
                          </el-link> -->
                        </p>
                        <!-- <el-option-group label=""
                          v-if="getSubTableFiled(activeData.config.relationTable).length">
                          <el-option disabled value="-">
                            <el-link type="primary" :underline="false" @click="openFieldDialog">添加字段
                            </el-link>
                          </el-option>
                        </el-option-group> -->
                        <el-option-group label="">
                          <el-option
                            v-for="item in getSubTableFiled(activeData.config.relationTable)"
                            :key="item.field" :value="item.field"
                            :label="item.fieldName?item.field+'('+item.fieldName+')':item.field">
                          </el-option>
                        </el-option-group>
                      </el-select>
                    </el-form-item>
                  </template>
                </template>
              </template>
              <template v-else>
                <template
                  v-if="activeData.config.pfKey==='calculate' ||activeData.config.pfKey==='popupAttr' ||activeData.config.pfKey==='relationFormAttr'">
                  <el-form-item label="控件用途">
                    <el-select v-model="activeData.config.isStorage" placeholder="请选择"
                      @change="changeStorage">
                      <el-option :label="item.label" :value="item.value"
                        v-for="(item,i) in storageType" :key="i"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
                <el-form-item label="控件字段"
                  v-if="activeData.vModel!==undefined  && !noVModelList.includes(activeData.config.pfKey)  ||activeData.config.isStorage==2">
                  <el-input v-model="activeData.vModel" placeholder="请输入数据库字段"
                    @change="inputFieldChange($event,activeData.config.formId,activeData.config.parentVModel)"
                    :disabled="activeData.config.pfKey==='table'" />
                </el-form-item>
              </template>
            <component :is="propertyComponent" :activeData="activeData" :drawingList="drawingList" />
            <el-form-item v-if=" !noVModelList.includes(activeData.config.pfKey) && activeData.config.pfKey !== 'codingRules'"
                    label="用于编码">
              <el-switch v-model="activeData.config.codeUse" />
            </el-form-item>
          </template>
          
        </el-form>
          <ComponentStyle :formConf = formConf v-show="currentTab === 'style'" />
      </el-scrollbar>
    </div>
    <!-- <field-dialog
      :visible.sync="fieldDialogVisible"
      ref="fieldDialog"
      @close="fieldDialogVisible = false"
      @updateOptions="updateFieldOptions"
    /> -->
  </div>
</template>

<script>
import { noVModelList, calculateItem, onlinePeculiarList } from '@/generator/comConfig'
import { inputComponents, selectComponents, systemComponents, layoutComponents } from '@/generator/config'
import { mapState } from "vuex";
import FieldDialog from "./FieldDialog";
import devFormService from "@/service/dev/DevFormService";
import ComponentStyle from "./componentStyle";

export default {
  inject: ["getShowType", "getFormInfo"],
  props: ['formConf','showField','modelType', 'webType','allTable','databaseid'],
  components: {
    FieldDialog,
    ComponentStyle
  },
  data() {
    return {
      // databaseid: '',
      tableData: {},
      hasTable: true,
      alltable: [],
      currentTab: "field",
      formScriptVisible: false,
      fieldDialogVisible: false,
      styleScriptVisible: false,
      noVModelList,
      allComps:  [...inputComponents, ...selectComponents, ...systemComponents, ...layoutComponents, calculateItem, ...onlinePeculiarList],
      storageType: [
        {
          label: '展示数据',
          value: 1
        }, {
          label: '存储数据',
          value: 2
        }],
        fieldOptions: [],
    };
  },
  computed: {
    ...mapState("designer", ["activeData","drawingList"]),
    propertyComponent() {
      const commonRightList = ['comSelect', 'depSelect', 'posSelect', 'userSelect', 'usersSelect', 'groupSelect', "roleSelect", 'editor']
      const systemList = ['createUser', 'createTime', 'modifyUser', 'modifyTime', 'currOrganize', 'currDept', 'currPosition', 'billRule', 'currCompany']
      const popupSelectList = ['popupTableSelect', 'popupSelect']
      if(this.activeData.config && this.activeData.config.pfKey && commonRightList.indexOf(this.activeData.config.pfKey)>-1){
        return 'ComRightProperty'
      }else if (this.activeData.config && this.activeData.config.pfKey && systemList.indexOf(this.activeData.config.pfKey)>-1){
        return 'isSystemProperty'
      }else if (this.activeData.config && this.activeData.config.pfKey && popupSelectList.indexOf(this.activeData.config.pfKey)>-1){
        return 'popupTableSelectProperty'
      }else {
        return (this.activeData.config.pfKey + "Property").trim()
      }
      // return this.activeData.config && this.activeData.config.pfKey
      //   ? (this.activeData.config.pfKey + "Property").trim()
      //   : "";
    },

    mainTable() {
      let allTable = this.allTable
      let item = allTable.filter(o => o.typeId == '1')[0]
      if (!item || !item.table) return ''
      return item.table
    },
  },
  watch: {
    activeData:{
      handler(val) {
        console.log(val)
        this.fieldOptions = []
        if(val.config.tableName!= ''){
          this.setDefaultOptions(val.config.tableName)
        } else {
          console.log(111111)
          this.activeData.config.tableName = this.allTable[0].tableName
          this.setDefaultOptions(this.allTable[0].tableName)
        }
      }
    }
  },
  created(){
    console.log(this.activeData,'active')
  },
  methods: {
    addStyle() {
      this.$nextTick(() => {
        this.styleScriptVisible = true
      })
    },
    // openFieldDialog() {
    //   let tableName = ''
    //   if (!this.activeData.config.isSubTable) {
    //     tableName = this.activeData.config.tableName
    //   } else {
    //     tableName = this.activeData.config.relationTable
    //   }
    //   let dataBase = this.$store.state.generator.dataBase || '0'
    //   this.fieldDialogVisible = true
    //   this.$nextTick(() => {
    //     this.$refs.fieldDialog.init(dataBase, tableName)
    //   })
    // },
    // async updateFieldOptions(data) {
    //   let tableName = ''
    //   if (!this.activeData.config.isSubTable) {
    //     tableName = this.activeData.config.tableName
    //   } else {
    //     tableName = this.activeData.config.relationTable
    //   }
    //   let queryType = 0, type = this.getFormInfo().type
    //   if (type == 3 || type == 4 || type == 5) queryType = 1
    //   let res = await DataModelFieldList(this.getFormInfo().dbLinkId, tableName, queryType)
    //   let fields = res.data.list
    //   for (let i = 0; i < this.allTable.length; i++) {
    //     if (this.allTable[i].table === tableName) {
    //       this.allTable[i].fields = fields
    //       break
    //     }
    //   }
    //   if (!this.activeData.config.isSubTable) {
    //     if (this.activeData.config.tableName === this.mainTable) this.formItemList = fields
    //     this.setDefaultOptions()
    //   } else {
    //     this.subTable = this.allTable.filter(o => o.typeId == '0')
    //   }
    // },
    tableChange(val) {
      console.log(this.allTable)
      console.log(val)
      this.activeData.vModel = ''
      this.setDefaultOptions(val)
    },
    async setDefaultOptions(val,id) {
      if (this.activeData.vModel === undefined || this.activeData.config.pfKey === 'table') return
      this.allTable.forEach(item=>{
        if(item.tableName == val) {
          this.fieldOptions = item.columns
        }
      })
    },
    changeStorage() {
      this.activeData.vModel = ''
      if (!this.hasTable && this.activeData.config.isStorage == 2) this.$emit('setVModel', this.activeData)
    },
    fieldChange(val) {
      if (!val) return
      const drawingList = this.drawingList || []
      let boo = false
      let aa = []
      const loop = list => {
        for (let i = 0; i < list.length; i++) {
          const e = list[i]
          const config = e.config
          if (e.vModel === val) {
            aa.push(val)
            if(aa.length>=2) {
              boo=true
              break
            }
          }
          if (config && config.pfKey != 'table' && config.children && Array.isArray(config.children)) {
            loop(config.children)
          }
        }
      }
      loop(drawingList)
      
      if (boo) {
        this.$message.warning(`字段【${val}】已存在,请重新选择!`)
        this.activeData.vModel = ''
        return
      }
      let item = this.fieldOptions.filter(o => o.columnHumpName == val)[0]
      if (!item || !item.columnHumpName) return
      this.activeData.config.label = item.remarks
    },
  },
};
</script>

<style lang='scss' scoped>
.right-board {
  width: 340px;
  position: absolute;
  right: 0;
  top: 0;
  padding-top: 3px;
  height: 100%;
  background: #fff;
  border-radius: 4px;
  .field-box {
    position: relative;
    height: calc(100% - 42px);
    box-sizing: border-box;
    overflow: hidden;
  }
  .el-scrollbar {
    height: 100%;
  }
}
.right-scrollbar {
  .el-form {
    >>> .el-date-editor,
    >>> .el-cascader,
    >>> .el-select {
      width: 100%;
    }
  }
}
</style>